import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

/*
本篇示例官方使用的是用http package发起简单的网络请求，但是http package功能较弱，很多常用功能都不支持。我们建议您使用dio 来发起网络请求，它是一个强大易用的dart http请求库，支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载……详情请查看github dio .
 */
class Post{
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({required this.userId, required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json){
    return Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}

Future<Post> fetchPost() async{
  final response = await http.get(Uri.dataFromString('https://jsonplaceholder.typicode.com/posts/1'));
  final responseJson = json.decode(response.body);
  return Post.fromJson(responseJson);
}

class HttpEx extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Fetch Data Example'),),
      body: Center(
        child: FutureBuilder<Post>(builder: (BuildContext context, AsyncSnapshot<Post> snapshot){
          if(snapshot.hasData){
            return Text(snapshot.data!.title);
          }else if(snapshot.hasError){
            return  Text('httpError:${snapshot.error}');
          }
          return CircularProgressIndicator();
        },
        future: fetchPost(),),
      ),
    );
  }
}